﻿using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;
using Spark.ServiceDiscovery.Remote;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;

namespace Spark.Ocelot.Remote.ServiceDiscovery
{
    public class RemoteServiceDiscoveryProvider : IServiceDiscoveryProvider
    {
        private readonly IRemoteClient _remoteClient;
        private readonly string _name;

        public RemoteServiceDiscoveryProvider(IServiceProvider provider
            , string name)
        {
            _remoteClient = provider.GetRequiredService<IRemoteClient>();
            _name = name;
        }

        public async Task<List<Service>> Get()
        {
            //从配置中心获取服务列表
            var list = _remoteClient.Services
                .Where(x => string.Equals(x.Name, _name, StringComparison.CurrentCultureIgnoreCase))
                .Select(x => new Service(x.Name, new ServiceHostAndPort(x.Ip, x.Port), x.Name, "", null))
                .ToList();

            return await Task.FromResult(list);
        }
    }
}